/*
 * ksAtomBlockWriter.cpp
 *
 *  Created on: Aug 3, 2011
 *      Author: wang
 */

#include "ksAtomBlockWriter.h"
#include <cstring>
#include <fstream>
#include "../ksDefines.h"
#include "../ksData.h"

ksAtomBlockWriter::ksAtomBlockWriter()
        : _data(NULL)
{
}

ksAtomBlockWriter::~ksAtomBlockWriter()
{
    delete[] _data;
}

unsigned int ksAtomBlockWriter::blockLength()
{
    return _blockHeader.atom.dataLength + kAtomBlockHeaderLength;
}
void ksAtomBlockWriter::prepare( int )
{
    // do nothing
}
void ksAtomBlockWriter::setData(unsigned char *data, unsigned int length)
{
    _blockHeader.atom.dataLength = length;
    _data = data;
}

void ksAtomBlockWriter::save(std::ofstream & out)
{
    LogObj("");
    description();
    LogObj("");
    std::cout << "ksAtomBlockWriter::save write at:" << out.tellp();
    // save header
    out.write((char*) &_blockHeader.atom, sizeof(_atomBlockHeader));
    std::cout << " header end:" << out.tellp();

    // save data
    out.write((char*) _data, _blockHeader.atom.dataLength);
    std::cout << " end:" << out.tellp();
    // write padding
    char padding[4] = { 0 };
    int paddingLength = _align4(_blockHeader.atom.dataLength) - _blockHeader.atom.dataLength;
    if (paddingLength != 0)
    {
        out.write(padding, paddingLength);
    }
    std::cout << " padding:" << out.tellp() << std::endl;
}
